--[[


   Save file format
Line			Value
---------------------
1				Money
2				Shield
3				Armor
4				Energy
5				Position X
6				Position Y
7				Party
8				Ship
9				Weapon table
10				Inventory


]]

firsttime=initArray2(32,true)

function unique(t)
	local r = {}
	local i = nil
	local n = 0
	for k,v in pairs(t) do
		if v~="" then
			r[#r+1] = v
		end
		i=v
	end
	return r
end

function string.split(t, b)
	local cmd = {}
	local match = "[^%s]+"
	if b then
		match = "%w+"
	end
	if type(b) == "string" then match = "[^"..b.."]+" end
	if not t then return invalid() end
	for word in string.gmatch(t, match) do
		table.insert(cmd, tonumber(word))
	end
	return cmd
end

function table.msg(t)
	local str=""
	for _,v in ipairs(t) do
		if (str=="") then
			str=str..v
		else
			str=str..","..v
		end
	end
	return str
end

function dataset(id,dn,d)
	local dd=tonumber(d)
	if (dn==1) then
		credits[id]=dd
	elseif (dn==2) then
		shield[id]=dd
	elseif (dn==3) then
		armor[id]=dd
	elseif (dn==4) then
		energy[id]=dd
	elseif (dn==5) then
		pos[id][1]=dd
	elseif (dn==6) then
		pos[id][2]=dd
	elseif (dn==7) then
		inParty[id][2]=dd
	elseif (dn==8) then
		shipt[id]=dd
	elseif (dn==9) then
		cwslots[id]=string.split(d,",")
	elseif (dn==10) then
		invslot[id]=string.split(d,",")
	end
end

function datanull(id)
	credits[id]=2000
	armor[id]=100
	shield[id]=100
	energy[id]=500
	pos[id]=spawnPos
	inParty[id]={false,0}
	shipt[id]=1
	cwslots[id]={1,0,0,0,0,0,0,0,0}
	invslot[id]={0,0,0}
	firsttime[id]=true
end

function datasave(id)
	if (player(id,"usgn")>0) then
		local usgn=player(id,"usgn")
		os.execute('touch "/home/engi/public_rpg/sys/lua/space_rpg/savedata/'..usgn..'.sav"')
		os.execute('chmod 666 "/home/engi/public_rpg/sys/lua/space_rpg/savedata/'..usgn..'.sav"')
		local m = assert(io.open('sys/lua/space_rpg/savedata/'..usgn..'.sav','w'))
		m:write(credits[id].."\n"..shield[id].."\n"..armor[id].."\n"..energy[id].."\n"..pos[id][1].."\n"..pos[id][2].."\n"..inParty[id][2].."\n"..shipt[id].."\n"..table.msg(cwslots[id]).."\n"..table.msg(invslot[id]))
		m:close()
		msg2(id,"Data save completed successfully!")
	else
		msg2(id,"Data save failed - not logged into USGN!")
	end
end

function dataread(id)
	if (player(id,"usgn")>0) then
		local usgn=player(id,"usgn")
		local m = assert(io.open('sys/lua/space_rpg/savedata/'..usgn..'.sav','r'))
			linen = 1
			lines = {}
			for line in m:lines() do
				msg("Line #"..linen..": "..line)
				dataset(id,linen,line)
				linen=linen+1
			end			
			m:close()
			msg2(id,"Data load completed successfully!")
	else
		msg2(id,"Data load failed - not logged into USGN!")
	end
end

addhook("join","player_load")
function player_load(id)
	dataread(id)
end

addhook("leave","player_save")
function player_save(id)
	datasave(id)
	datanull(id)
end